package game;
import gm.gmStringPrase;
import hibernateUtil.Gmtalkcontrol;
import io.OperationResponse;

import java.util.ArrayList;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import platform.AppConfig;
import platform.Platform;
import player.Player;
import protocol.GMParams;
import protocol.GMType;
import protocol.OpCode;
import protocol.ReturnCode;
import protomsg.Chat.ChatMsg;
import protomsg.Chat.ChatMsg2;
import protomsg.Chat.ChatType;
import protomsg.Rpc.ServerID;
import util.CommonTool;
import Public.PlayerPublicFun;
import Public.PublicFunction;

/**
 *
 */

public class ChatRoller {
	protected static final Logger log = LoggerFactory.getLogger(ChatRoller.class);
	/**
	 * ����
	 * @param operationRequest
	 */
    public static void SendTVMessage(ChatMsg operationRequest,Player player)
    {
        try
        {
            if (operationRequest != null)
            {

                String messageText = operationRequest.getText();
                if (!messageText.equals(""))
                {
                	
                	ArrayList<Player> listPlayers=new ArrayList<Player>();
                	listPlayers.addAll(PlayerPublicFun.onLineActors.values());                    
                	for (int i=0;i<listPlayers.size();i++) {
                		try{
                			if(listPlayers.get(i)!=null)
    						{
    							PublicFunction.OnEventTVMessage(String.format("[ffff00]%1$s[-]{0}",player.myTable.getPlayerName())+messageText,listPlayers.get(i),false);
    						}
                		}catch(Exception ex){
                			log.debug("���������쳣��"+ex.toString());
                		}
						
					}
                	                  
                }
            }
        }
        catch (Exception ex)
        {
        	log.debug("���������쳣��"+ex.toString());
        }
    }
    /**
     * ����
     */
    public static void OnRevSendMessage(ChatMsg recMsg,Player player)
    {
        try
        {
            if (recMsg != null)
            {
                int messageType = recMsg.getType().getNumber();
                String messageText = recMsg.getText();
                
                //如果是gm指令就返回
               if(gmStringPrase.prase(messageText,player)){
            	   
            	   return;
               }
                 
                java.util.List<String> bodys = recMsg.getBodysList();
                String[] messageBodys = new String[bodys.size()];
                bodys.toArray(messageBodys);
                
                ChatMsg2.Builder res;
                byte[] sendData;
                
                String messageSender = recMsg.getSender();

                Gmtalkcontrol gmtalkcontrol = Platform.getServiceManager().getDbService().gmtalkcontrolDao.GetTalkForID(player.myTable.getPlayerID());
               
                if (messageType == MessageType.Guild)
                {
                	if(gmtalkcontrol!=null && gmtalkcontrol.getGuildTalk()==1)
                	{
	         		 	res = ChatMsg2.newBuilder();
	         		 	
	         		 	res.setText(AppConfig.CH.get("info002"));
	         		 	res.setType(ChatType.Guild);
	         		 	res.setSender(AppConfig.CH.get("info001"));
	         		 	res.setSenderId(player.myTable.getPlayerID().toString());
	         		 	
	         		 	sendData = CommonTool.formatSendMsg(ServerID.Chat_VALUE, res.build().toByteArray());
	         		 	player.session.send(sendData);
	         		 	
                		return;
                	}else{
	                    if (Platform.getServiceManager().getDbService().guildinfoDao.GetGuildForID(Integer.parseInt(player.myTable.getGuildID()))!=null&&Platform.getServiceManager().getDbService().guildinfoDao.GetGuildForID(Integer.parseInt(player.myTable.getGuildID())).getIsDelete()!=1)
	                    {
	                        if (Platform.getServiceManager().getDbService().guildinfoDao.GetGuildForID(Integer.parseInt(player.myTable.getGuildID())).getStopTalkID().indexOf(player.myID)!=-1)
	                        {
	                            return;
	                        }
	                        else
	                        {	                        	
	                            messageBodys = Platform.getServiceManager().getDbService().guildinfoDao.GetGuildForID(Integer.parseInt(player.myTable.getGuildID())).getMemverID().split("[;]", -1);
	                        }
	                    }
	                    else
	                    {
	                        messageBodys = new String[1];
	                        messageBodys[0] = player.myID;
	                    }
                	}
                }
                else if (messageType == MessageType.Team)
                {
                	if(gmtalkcontrol!=null&&gmtalkcontrol.getTeamTalk()==1)
                	{
	         		 	res = ChatMsg2.newBuilder();
	         		 	
	         		 	res.setText(AppConfig.CH.get("info002"));
	         		 	res.setType(ChatType.Team);
	         		 	res.setSender(AppConfig.CH.get("info001"));
	         		 	res.setSenderId(player.myTable.getPlayerID().toString());
	         		 	
	         		 	sendData = CommonTool.formatSendMsg(ServerID.Chat_VALUE, res.build().toByteArray());
	         		 	player.session.send(sendData);
	         		 	
                		return;
                	}else{
	                    if (player.MyTeam!=null)
	                    {
	                        messageBodys = new String[player.MyTeam.listActors.size()];
	                        int num = 0;
	                        for (String mID : player.MyTeam.listActors.keySet())
	                        {
	                            messageBodys[num] = mID;
	                            num++;
	                        }
	                    }	
	                    else
	                    {
	                    	return;
//	                        messageBodys = new String[1];
//	                        messageBodys[0] = player.myID;
	                    }
                	}
                }

                ChatMsg2.Builder parameter = ChatMsg2.newBuilder();
     		 	
                parameter.setText(messageText);
                parameter.setType(recMsg.getType());
                parameter.setSender(messageSender);
                parameter.setSenderId(player.myTable.getPlayerID().toString());
     		 	
     		 	byte[] sendParameterData = CommonTool.formatSendMsg(ServerID.Chat_VALUE, parameter.build().toByteArray());
               
                //log.DebugFormat("�����¼�ǰ:{0}", messageBodys.Length);
              //  short event = (Short)operationRequest.Parameters.get(EventCode.SendMessage);
                if (messageType == MessageType.Somebody)
                {
                	if(messageBodys[0].equals("0"))
            		{
            			HashMap<Short, Object> dicsend = new HashMap<Short, Object>();
            			dicsend.put(GMParams.GMUserID,player.GMName);
            			dicsend.put(GMParams.GMType, GMType.GMChat);
            			dicsend.put(GMParams.MailText,messageText);
            			 
            			OperationResponse toGM = new OperationResponse(OpCode.GMgameBack,dicsend, ReturnCode.Yes,"");
            			player.GMSession.SendOperationResponse(toGM);
            		}
                	if(gmtalkcontrol!=null&&gmtalkcontrol.getSomebodyTalk()==1)
                	{
                		if(messageBodys[0].equals("0"))
                		{       			
    	         		 	player.session.send(sendParameterData);
    	         		 	
                		}else {
	                        
	                        res = ChatMsg2.newBuilder();
		         		 	
		         		 	res.setText(AppConfig.CH.get("info002"));
		         		 	res.setType(ChatType.Somebody);
		         		 	res.setSender(AppConfig.CH.get("info001"));
		         		 	res.setSenderId(player.myTable.getPlayerID().toString());
		         		 	
		         		 	sendData = CommonTool.formatSendMsg(ServerID.Chat_VALUE, res.build().toByteArray());
		         		 	player.session.send(sendData);
	                        
	                    	return;
                		}
                	}else{
                		
	         		 	player.session.send(sendParameterData);
                	}
	//                    this.SendEvent(@event, sendParameters);
                }
                
                if(gmtalkcontrol!=null&&gmtalkcontrol.getGuildTalk()==1&&gmtalkcontrol.getNomalTalk()==1&&gmtalkcontrol.getSomebodyTalk()==1&&gmtalkcontrol.getTeamTalk()==1)
            	{
                    res = ChatMsg2.newBuilder();

                    res.setText(AppConfig.CH.get("info002"));
                    res.setType(recMsg.getType());
                    res.setSender(AppConfig.CH.get("info001"));
                    res.setSenderId(player.myTable.getPlayerID().toString());

                    sendData = CommonTool.formatSendMsg(ServerID.Chat_VALUE, res.build().toByteArray());
         		 	
            		return;
            	}else{
                
	                ArrayList<Player> listPlayers=new ArrayList<Player>();
	            	listPlayers.addAll(PlayerPublicFun.onLineActors.values());   
	                
	                for (int i=0;i<listPlayers.size();i++) 
	                {
	                	if(listPlayers.get(i)!=null){
	                	
	                		ChatMsg2 bmsg2 = parameter.build();
	                		short param1 = ServerID.Chat_VALUE;
	                	
	                		OnBroadcaseMessage(messageBodys,messageType, bmsg2, param1,param1 , listPlayers.get(i));
	                	}
					}
            	}

            }
        }
        catch (Exception ex)
        {
        	log.debug("��������쳣��"+ex.toString());
        }

    }
    
    
    /**
     * ����ϵͳ��Ϣ�������
     * @param messageText
     * @param messageBodys
     */
    public static void SendMessage(String messageText, String[] messageBodys)
    {
         ChatMsg2.Builder res = ChatMsg2.newBuilder();
         res.setText(messageText);
         res.setType(ChatType.System);
         
         byte[] sendData = CommonTool.formatSendMsg(ServerID.Chat_VALUE, res.build().toByteArray());
    	
         
         Player player=null;
         for (String str : messageBodys)
         {
             if (PlayerPublicFun.onLineActors.containsKey(Integer.parseInt(str)))
             {
                 player = PlayerPublicFun.onLineActors.get(Integer.parseInt(str));
           		 
           		 player.send(sendData);
             }
         }
         
    }
    
    
    /**
     * ����ϵͳ��Ϣ�������
     * @param messageText
     * @param messageBodys
     */
    public static void SendMessage(String messageText, ArrayList<Player> messageBodys)
    {
         ChatMsg2.Builder res = ChatMsg2.newBuilder();
         res.setText(messageText);
         res.setType(ChatType.System);
         
         byte[] sendData = CommonTool.formatSendMsg(ServerID.Chat_VALUE, res.build().toByteArray());
    	
         
         for (Player player : messageBodys)
         {
           		 player.session.send(sendData);
               
         }
         
    }
    
/**
 * �㲥��Ϣ
 */
    
    private static void OnBroadcaseMessage(String[]userName,int messageType,ChatMsg2 parameter, short eventDate,short opCode,Player player )
    {
        try
        {
        	byte[] sendData;
        	
            switch (messageType)
            {
                case MessageType.All:
                    {
                        	sendData = CommonTool.formatSendMsg(opCode,parameter.toByteArray());
                        	player.session.send(sendData);
                    }
                    break;
                case MessageType.Somebody:
                case MessageType.Team:
                case MessageType.Guild:
                    {
                        for (String str : userName)
                        {
                            if (PlayerPublicFun.onLineActors.containsKey(Integer.parseInt(str)))
                            {
                                if (PlayerPublicFun.onLineActors.get(Integer.parseInt(str))==player)
                                {
                          		 	sendData = CommonTool.formatSendMsg(opCode,parameter.toByteArray());
                                	player.session.send(sendData);
                                	
                                    break;

                                }
                            }
                        }
                    }
                    break;
            }
        }
        catch(Exception ex)
        {
        
        }
    }
//    /**
//     * ����GM��Ϣ
//     */
//    private void SendGMTV(OperationResponse operationRequest)
//    {
//        String messageText = (String)operationRequest.Parameters.get(ParameterType.MessageText);
//        if (!messageText.isEmpty())
//        {
//            //EventTVMessage(messageText);
//            for (int i = 0; i < PlayerPublicFun.onLineActors.size(); i++)
//            {
//                try
//                {
//                	PublicFunction.OnEventTVMessage(messageText, PlayerPublicFun.onLineActors.get(i));
//                }
//                catch (Exception ex)
//                {
//                    
//                }
//            }
//        }
//    }
    /**
     *  ����GM��Ϣ
     */
    
    public static void SendGMTV(String mText,boolean isSystem)
    {
    	SendGMTVFiber(mText,isSystem);
    }
    
    
    private static void SendGMTVFiber(String mText,boolean isSystem)
    {
        String messageText = mText;
        if (!mText.isEmpty())
        {
            //EventTVMessage(messageText);
        	
//        	for (Player player : PlayerPublicFun.onLineActors.values())
//			{
//                try
//                {
//                	PublicFunction.OnEventTVMessage(messageText, player);
//                }
//                catch (Exception ex)
//                {
//                   log.error(ex.toString());
//                }
//			}
        	
        	ArrayList<Player> listPlayers=new ArrayList<Player>();
        	listPlayers.addAll(PlayerPublicFun.onLineActors.values());
            for (int i = 0; i < listPlayers.size(); i++)
            {
                try
                {
                	PublicFunction.OnEventTVMessage(messageText, listPlayers.get(i),isSystem);
                }
                catch (Exception ex)
                {
                   log.error(ex.toString());
                }
            }
        }
    }
    
    public static void SendGMTVFiber(String mText,boolean isSystem,String[] listPlayerID)
    {
        String messageText = mText;
        if (!mText.isEmpty())
        {
        	
        	ArrayList<Player> listPlayers=new ArrayList<Player>();
        	
        	Player player;
        	for (String playerID : listPlayerID)
			{
				if(!playerID.isEmpty())
				{
					player=PlayerPublicFun.onLineActors.get(Integer.parseInt(playerID));
					if(player!=null)
					{
						listPlayers.add(player);
					}
				}
			}
        	
            for (int i = 0; i < listPlayers.size(); i++)
            {
                try
                {
                	PublicFunction.OnEventTVMessage(messageText, listPlayers.get(i),isSystem);
                }
                catch (Exception ex)
                {
                   log.error(ex.toString());
                }
            }
        }
    }
    
    
    
    
    
    
    
    


	
}
